package com.yhzl.two.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yhzl.two.shop.common.ServerResponse;
import com.yhzl.two.shop.common.ServiceCommonMethod;
import com.yhzl.two.shop.entity.Product;
import com.yhzl.two.shop.entity.ShopCart;
import com.yhzl.two.shop.mapper.ProductMapper;
import com.yhzl.two.shop.mapper.ShopCartMapper;
import com.yhzl.two.shop.service.IShopCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chsm
 * @since 2018-09-07
 */
@Service
public class ShopCartServiceImpl extends ServiceImpl<ShopCartMapper, ShopCart> implements IShopCartService {

    private final ProductMapper productMapper;

    @Autowired
    public ShopCartServiceImpl(ProductMapper productMapper) {
        this.productMapper = productMapper;
    }

    @Override
    public ServerResponse<String> add(ShopCart shopCart) {
        ShopCart oldShopCart = baseMapper.selectOne(new QueryWrapper<ShopCart>()
                .eq("uid", shopCart.getUid())
                .eq("pid", shopCart.getPid()));
        // 校验当前购物车是否存在该商品，存在则更新否则添加
        if (oldShopCart == null) {
            baseMapper.insert(shopCart);
        } else {
            Product product = productMapper.selectById(shopCart.getPid());
            Integer sumNum = oldShopCart.getNum() + shopCart.getNum();
            if (sumNum > product.getStock()) {
                return ServerResponse.createErrorMessage("商品库存不足");
            }
            baseMapper.updateById(oldShopCart.setNum(sumNum));
        }
        return ServerResponse.createSuccessMessage("添加购物车成功");
    }

    @Override
    public ServerResponse<String> delete(Integer id) {
        int count = baseMapper.deleteById(id);
        return ServiceCommonMethod.returnInsert(count, "删除成功", "删除失败");
    }

    @Override
    public ServerResponse<String> update(ShopCart shopCart) {
        int count = baseMapper.updateById(shopCart);
        return ServiceCommonMethod.returnInsert(count, "更新成功", "更新失败");
    }

    @Override
    public ServerResponse<List<ShopCart>> queryByUid(Integer uid) {
        List<ShopCart> shopCarts = baseMapper.queryByUid(uid);
        return ServerResponse.createSuccessData("获取信息成功", shopCarts);
    }
}
